package impl

import (
	"entry_task/entry_core/src/db"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"gopkg.in/ini.v1"
	"os"
	"sync"
	"time"
)

type dbSourceManagerImpl struct {
	dbSourceMap *sync.Map
}

func (impl *dbSourceManagerImpl) GetDbSource(name string) *xorm.Engine {
	value, ok := impl.dbSourceMap.Load(name)
	if !ok {
		panic("GetDbSource.(*xorm.Engine) error name:" + name)
	}
	source, ok := value.(*xorm.Engine)
	if !ok {
		panic("value.(*xorm.Engine) error")
	}
	return source
}

func (impl *dbSourceManagerImpl) AddDbSource(name string) *xorm.Engine {

	cfg, err := ini.Load("/Users/yuliao.chen/go/src/go_entry_task/entry_core/src/config/dev.ini") //初始化一个cfg
	if err != nil {
		fmt.Printf("Fail to read file: %v", err)
		os.Exit(1)
	}
	config := new(db.DatabaseConfig)
	err = cfg.Section(name).MapTo(config)
	engine := buildEngine(config)
	impl.dbSourceMap.Store("mysql", engine)
	return engine
}

func buildEngine(config *db.DatabaseConfig) *xorm.Engine {
	url := fmt.Sprintf("%s:%s@tcp(%s:%d)/entry_task_db?charset=utf8mb4&parseTime=True&loc=Local",
		config.Username, config.Password, config.Host, config.Port)
	fmt.Printf("data base url: %s\n", url)

	engine, err := xorm.NewEngine("mysql", url)
	if err != nil {
		panic("数据库连接异常")
	}
	engine.SetMaxOpenConns(config.MaxOpenConn)
	engine.SetMaxIdleConns(config.MaxIdleConn)
	engine.SetConnMaxLifetime(time.Duration(config.ConnMaxLifeTime) * time.Second)
	engine.ShowSQL(true)
	engine.ShowExecTime(true)
	return engine
}
